package com.jied.duodian.web;

import com.jied.duodian.entity.Dutity.DdOUser;
import com.jied.duodian.service.Impl.AuthServiceImpl;
import com.jied.duodian.util.CommonResult;
import com.jied.duodian.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Description:
 *
 * @author LiJie
 * @date Created on 2020/10/30
 * WWW https://github.com/j6l
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    @Autowired
    AuthServiceImpl authService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    /**
     * 登录
     *
     * @param ddOUser
     * @return
     * @throws AuthenticationException
     */
    @PostMapping("/auth")
    public CommonResult createAuthenticationToken(
            @RequestBody DdOUser ddOUser) throws AuthenticationException {
        final String token = authService.login( ddOUser.getUsername(), ddOUser.getPassword() );
        if (token == null)
            return CommonResult.failed( "用户被封禁或者账号密码错误!" );
        // Return the token
        return CommonResult.success( token );
    }

    /**
     * 刷新token
     *
     * @param request
     * @return
     * @throws AuthenticationException
     */
    @GetMapping("/refresh")
    public CommonResult refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws AuthenticationException {
        String token = request.getHeader( jwtTokenUtil.getTokenHead() );
        String refreshedToken = authService.refresh( token );
        if (refreshedToken == null) {
            return CommonResult.failed( "token失效,请重新登录!" );
        } else {
            return CommonResult.success( token );
        }
    }
}
